# -*-coding:utf-8-*-
import json
from functools import wraps
import requests
from requests.utils import cookiejar_from_dict
import time

"""
https://cdn.xingshui.chinatax.gov.cn/transCode/mp4/a6283c64-b218-4a60-8b08-7c9a0cc9ef05/course/video/t4jEtn5N7j1637627874239.mp4
https://cdn.xingshui.chinatax.gov.cn/a6283c64-b218-4a60-8b08-7c9a0cc9ef05\/speciallearning\/document\/wpF3b3WRjA1607583170345.doc
course下面包含一或多个lesson;
courseid为课程course列表中的target_id
lessonid为lesson列表中的uuid
一、将抓包获取的courseid放入脚本所在目录的人course.txt中（换行分开每个courseid）
二、需要抓包修改的数据：
    1.header的Authorization
    2.cookie
    3.add_course函数post的from参数
"""

# 设置全局header和cookie
headers = {
    "Authorization": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJoYW50ZSIsImF1ZCI6ImhhbnRlIiwiaWF0IjoxNjU2OTg0MDk3LCJleHAiOjE2NTk1NzYwOTcsImNvbXBhbnlfaWQiOiJhNjI4M2M2NC1iMjE4LTRhNjAtOGIwOC03YzlhMGNjOWVmMDUiLCJ1c2VyX2lkIjoiR0VfMTdjNDY0OWZlYjFjNDM1NzgyODUxOTRkYTgyZTNkYmEiLCJmcm9tX2lkIjoyMzYxMDkyMywiZGVwdF91c2VyX2lkIjoiR0VfMTdjNDY0OWZlYjFjNDM1NzgyODUxOTRkYTgyZTNkYmEifQ.iURDyvDYc9zFOQ4L8cmKPjXj-LhCrC-DuJ78extC1ig",
    "User-Agent": "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 "
                  "Safari/537.36 dingtalk-win/1.0.0 nw(0.14.7) DingTalk(1.3.202-Release.5) Mojo/1.0.0 Native AppTyp"
                  "e(release)"}
cookies = {"acw_tc":"276aede616569840962507510e551b6ff54c0fdfedc8501d9aa4a8f4a7fb1f"}
session = requests.Session()
session.headers = headers
session.cookies = cookiejar_from_dict(cookies)


# 设置抓包代理
# session.proxies = {'http': 'http://127.0.0.1:8080'}
# session.verify = False

def sleep(t=0.0):
    """函数延时装饰器

    :param t: 延时时间
    """

    def wrapper(func):
        @wraps(func)
        def inner_wrapper(*args, **kwargs):
            time.sleep(t)
            r = func(*args, **kwargs)
            return r

        return inner_wrapper

    return wrapper


def add_course(courseid):
    """1.添加课程
    """
    get = {"utcoffset": "-28800", "lang": "zh"}
    # from参数：一般课程为course, 培训为special_learning, 不同课程需抓课程学习页面的”加入学习“操作的包
    post = {"course_id": courseid, "from": "special_learning"}
    response = session.post("https://xingshui.chinatax.gov.cn/NewSoke/course/home/v1/courseUser", data=post, params=get)
    print('===>添加course', response.json()['status'])


def get_lesson_info(courseid):
    """2.获取course下所有的lesson信息

    返回的json主要字段信息：
    type为video|document|test, 需要将test类型过滤掉
    [{
    "uuid": "D3613C8F-5FBD-4C39-A5E3-CC3252087F9C",
    "title": "第一集 《意见》要义",
    "type": "video",
    "course_id": "91B04115-5A95-49EB-85CB-4FBB5E2D97C1",
    "length": 290,
    "progress": 0,
    }, ]

    :return lesson的id,时长,类型组成的列表
    """
    get = {"utcoffset": "-28800", "course_id": courseid, "lang": "zh"}
    js = session.get("https://xingshui.chinatax.gov.cn/NewSoke/course/home/v1/courseLesson", params=get).json()
    print('===>获取lessonid', js['status'])
    list_lesson = [(s['uuid'], s['length'], s['type']) for s in js['data']['list'] if
                   s['type'] == 'video' or s['type'] == 'document']
    return list_lesson


@sleep(0.5)
def start_lesson(lessonid):
    """3.开始学习
    """
    get = {"utcoffset": "-28800", "lang": "zh", "lesson_id": lessonid}
    js = session.get("https://xingshui.chinatax.gov.cn/NewSoke/course/home/v1/courseLessonLearn/startLearn",
                     params=get).json()
    print('=====>开始学习', js['status'])


@sleep(0.5)
def post_time(lessonid, length, lesson_type):
    """4.提交时间

    类型为video时post参数为learn_time,playing,lesson_id,current_time;
    类型为document时post参数为learn_time,playing,lesson_id,current_time,current_page.
    """
    get = {"utcoffset": "-28800", "lang": "zh"}
    post = {"learn_time": length, "playing": "true", "lesson_id": lessonid, "current_time": length}
    if lesson_type == 'document':
        post["current_page"] = 0
        post["playing"] = 'false'
    js = session.post("https://xingshui.chinatax.gov.cn/NewSoke/course/home/v1/courseLessonLearn/updateWatchTime",
                      data=post, params=get).json()
    print('=====>提交时间', js['status'])


@sleep(0.5)
def finish_lesson(courseid, lessonid):
    """5.完成学习
    """
    get = {"utcoffset": "-28800", "course_id": courseid, "lang": "zh", "lesson_id": lessonid}
    js = session.get("https://xingshui.chinatax.gov.cn/NewSoke/course/home/v1/courseLessonLearn/finishLearn",
                     params=get).json()
    print('=====>完成学习', js['status'])


def main():
    with open('course.txt', 'r') as f:
        for line in f:
            courseid = line.strip()
            print('\n=>学习course', courseid)
            add_course(courseid)
            for lessonid, length, lesson_type in get_lesson_info(courseid):
                print('===>学习lesson', lessonid)
                start_lesson(lessonid)
                post_time(lessonid, length, lesson_type)
                finish_lesson(courseid, lessonid)


# 从试题json中提取出题目
def get_exam_from_json():
    data = json.load(open(r'a.json', 'r', encoding='utf8'))
    items = data['data']['items'].values()
    exam = '\n\n'.join(str(i['weight']) + '.' + i['title'] for i in items)
    with open(r'course.txt', 'w') as f:
        f.write(exam)


if __name__ == '__main__':
    main()
